<?php
class Send extends MY_Controller
{
	public function __construct()
	{
		log_message('debug', '=====开始调用Mail->Send->__construct接口=====');
		parent::__construct();
		$this->loadLanguageFile('application/controllers/Mail/');
		log_message('debug', '=====调用Mail->Send->__construct接口结束=====');
	}
	
	public function showView() {
		$this->load->view('module/Mail/send.htm');
	}
	
	public function getListData() {
		log_message('debug', '=====开始调用Mail->Send->getListData接口=====');
		$this->verifyPrivilege();
		
		try{
			$page = $this->param->getParam('page', array('method' => 'int', 'min' => 1, 'emptyErrorCode' => 1, 'invalidErrorCode' => 1));
			$rows = $this->param->getParam('rows', array('method' => 'int', 'min' => 1, 'emptyErrorCode' => 1, 'invalidErrorCode' => 1));
			$sql = "
				select
					<selectColumns>
				from
					`t_data_send_mail` a
				left join
					`t_data_user` b
				on
					a.`applyUserId` = b.`userId`
				left join
					`t_data_user` c
				on
					a.`approvalUserId` = c.`userId`
                where 
                    c.`userId`={$this->currUserId} 
                or 
                    b.`userId`={$this->currUserId}
			";
			$getTotalSql = str_replace('<selectColumns>', "count(*)", $sql);
			$this->returnData['data']['total'] = $this->gmDatabase->getColumn($getTotalSql);
			$getDataSql = str_replace('<selectColumns>', "a.`applyId`, a.`roleName`, concat(if(a.`minRoleLevel` is NULL, 'min', a.`minRoleLevel`) , ' - ', if(a.`maxRoleLevel` is NULL, 'max', a.`maxRoleLevel`)) as `roleLevel`, a.`senderName`, a.`title`, a.`content`, a.`status`, b.`name` as `applyUserName`, a.`applyDatetime`, c.`name` as `approvalUserName`, a.`approvalDatetime`", $sql);
				
			if($page && $rows) {
				$startRow = ($page - 1) * $rows;
				$getDataSql .= " limit {$startRow}, {$rows}";
			}
			
			$tmpArray = $this->gmDatabase->getArray($getDataSql);
			
			foreach ($tmpArray as $key => $val) {
				$sql = "
					select
						`item{$this->currLanguage}Name` as itemName,
						sum(`itemCount`) as `itemCount`
					from
						`t_data_send_mail_attachment` a
					left join
						`t_cfg_item` b
					on
						a.`itemId` = b.`id`
					where
						a.`applyId` = '{$val['applyId']}'
					group by
						b.`id`
						
				";
				$itemArray = $this->gmDatabase->getArray($sql);
				
				$itemString = '';
				
				foreach ($itemArray as $k => $v) {
					$itemString .= "{$v['itemName']} * {$v['itemCount']}</br>";
				}
				
				$tmpArray[$key]['item'] = $itemString;
			}
			
			$this->returnData['data']['rows'] = $tmpArray;
		}
		
		catch(MY_Param_Exception $e) {
			$this->setErrorCode($e->getCode());
		}
		
		catch(MY_Mysql_Exception $e) {
			$this->setErrorCode(1);
		}
		
		catch(Exception $e) {
			$this->setErrorCode($e->getCode());
		}
		
		$this->returnJson();
		log_message('debug', '=====调用Mail->Send->getListData接口结束=====');
	}

	private function mailPrivilege()
	{
		log_message('debug', '=====开始调用Mail->Send->mailPrivilege接口=====');
		$userId = $this->currUserId;
		if($userId > 1) {
			$sql = "
				select
					count(*)
				from
					`t_data_user_menu_privilege`
				where
					`userId` = '{$userId}'
					and
					`menuId` in
					(
						select
							`menuId`
						from
							`t_cfg_menu`
						where
							menuId = '20102'
					)
					and
					`privilegeValue` = 1
			";
			if($this->gmDatabase->getColumn($sql) === '0') {
				$this->setErrorCode(102);
				$this->returnJson();
				exit();
			}
		}

		log_message('debug', '=====调用Mail->Send->mailPrivilege接口结束=====');
	}

	public function apply() {
		log_message('debug', '=====开始调用Mail->Send->apply接口=====');
		$this->verifyPrivilege();
		try{
			$gameAreaIdString = $this->param->getParam('gameAreaIdString', array('method' => 'string', 'emptyErrorCode' => 201, 'invalidErrorCode' => 1));
			$roleName = $this->param->getParam('roleName', array('method' => 'string', 'emptyErrorCode' => 1, 'invalidErrorCode' => 1), 'post', true);
			$minRoleLevel = $this->param->getParam('minRoleLevel', array('method' => 'int', 'min' => 1, 'emptyErrorCode' => 1, 'invalidErrorCode' => 1), 'post', true);
			$maxRoleLevel = $this->param->getParam('maxRoleLevel', array('method' => 'int', 'min' => 1, 'emptyErrorCode' => 1, 'invalidErrorCode' => 1), 'post', true);
			$senderName = $this->param->getParam('senderName', array('method' => 'string', 'maxLength' => 255, 'emptyErrorCode' => 201001, 'invalidErrorCode' => 1));
			$title = $this->param->getParam('title', array('method' => 'string', 'maxLength' => 255, 'emptyErrorCode' => 201002, 'invalidErrorCode' => 1));
			$content = $this->param->getParam('content', array('method' => 'string', 'maxLength' => 2048, 'emptyErrorCode' => 1, 'invalidErrorCode' => 1), 'post', true);
			$itemString = $this->param->getParam('itemString', array(), 'post', true);
			$itemString2 = "";
			
			$this->gmDatabase->closeAutoCommit();
			
			$itemArray;
			if($itemString) {
			    //获取申请物品权限
			    $this->mailPrivilege();
			    $itemArray = json_decode($itemString, true);
			}
			
			foreach($itemArray as $item) {
			    $id = $item['id'];
			    $itemCount = $item['count'];
			    $sql = "select itemId from t_cfg_item where id='$id'";
			    $result = $this->gmDatabase->getRow($sql);
			    $itemRefId = $result['itemId'];
			    if($itemString2 === "")
			    {
			        $itemString2 = $itemRefId."_".$itemCount;
			    }else
			    {
			        $itemString2 = $itemString2.";".$itemRefId."_".$itemCount;
			    }
			}
			
			$sql = "
				insert into
					`t_data_send_mail`
				set
					`roleName` = '{$roleName}',
					`senderName` = '{$senderName}',
					`title` = '{$title}',
					`content` = '{$content}',
                    `itemString` = '{$itemString2}',
					`status` = '1',
					`applyUserId` = '{$this->currUserId}',
					`applyDatetime` = now()
			";
			
			if($minRoleLevel <> '') {
				$sql .= ", `minRoleLevel` = {$minRoleLevel}";
			}
			
			if($maxRoleLevel <> '') {
				$sql .= ", `maxRoleLevel` = {$maxRoleLevel}";
			}
			
			$this->gmDatabase->query($sql);
			
			$applyId = $this->gmDatabase->getLastInsertId();
			log_message('debug', "applyId:{$applyId}");
			
			$gameAreaIdArray = explode(',', $gameAreaIdString);
			
			foreach ($gameAreaIdArray as $gameAreaId) {
				$sql = "
					insert into
						`t_data_send_mail_game_area`
					(
						`applyId`,
						`gameAreaId`,
						`status`
					)
					select 
						'{$applyId}',
						'{$gameAreaId}',
						'1'
					from
						`t_data_game_area` a
					left join
						`t_data_user_operator_privilege` b
					on
						a.`operatorId` = b.`operatorId`
						and
						b.`userId` = '{$this->currUserId}'
					where
						a.`gameAreaId` = '{$gameAreaId}'
						and
						b.`privilegeValue` = 1
				";
				$this->gmDatabase->query($sql);
			}
				
			foreach($itemArray as $item) {
			    $itemId = $item['id'];
			    $itemCount = $item['count'];
			    
			    $sql = "
						select
							`maxCount`
						from
							`t_cfg_item`
						where
							`id` = '{$itemId}'
					";
			    
			    if( ! (($row = $this->gmDatabase->getRow($sql)) === false) ) {
			        $maxCount = $row['maxCount'];
			        
			        for($i = $itemCount; $i > $maxCount; $i = $i - $maxCount) {
			            $sql = "
								insert into
									`t_data_send_mail_attachment`
								(
									`applyId`,
									`itemId`,
									`itemCount`
								)
								value
								(
									'{$applyId}',
									'{$itemId}',
									'{$maxCount}'
								)
							";
			            $this->gmDatabase->query($sql);
			        }
			        
			        $sql = "
							insert into
								`t_data_send_mail_attachment`
							(
								`applyId`,
								`itemId`,
								`itemCount`
							)
							value
							(
								'{$applyId}',
								'{$itemId}',
								'{$i}'
							)
						";
			        $this->gmDatabase->query($sql);
			    }
			}
			
			$this->gmDatabase->commit();
		}
		
		catch(MY_Param_Exception $e) {
			$this->setErrorCode($e->getCode());
		}
	
		catch(MY_Mysql_Exception $e) {
			$this->gmDatabase->rollback();
			$this->setErrorCode(1);
		}
		
		catch(Exception $e) {
			$this->setErrorCode($e->getCode());
		}
		
		$this->gmDatabase->openAutoCommit();
		$this->returnJson();
		log_message('debug', '=====调用Mail->Send->apply接口结束=====');
	}
	
	public function approval() {
		error_log("approval ---------------------");
		//log_message('debug', '=====开始调用Mail->send->approval接口=====');
		$this->verifyPrivilege();
		try {
			$applyId = $this->param->getParam('applyId', array('method' => 'int', 'min' => 1, 'emptyErrorCode' => 1, 'invalidErrorCode' => 1));
			$status = $this->param->getParam('status', array('method' => 'int', 'min' => 2, 'max' => 3, 'emptyErrorCode' => 1, 'invalidErrorCode' => 1));
			error_log("approval status = ".$status);
			
			if($status == 2)
			{
    			$sql = "select * from t_data_send_mail where applyId = '{$applyId}' and status = '1'";
    			$result = $this->gmDatabase->getRow($sql);
                
    			
    			$roleName = urlencode($result['roleName']);
    			$minRoleLevel = $result['minRoleLevel'];
    			$maxRoleLevel = $result['maxRoleLevel'];
    			$itemString = $result['itemString'];
    			$title = $result['title'];
    			$content = $result['content'];
    			
    			$sql = "select gameAreaId from t_data_send_mail_game_area where applyId = '{$applyId}'";
    			$areaArr = $this->gmDatabase->getArray($sql);
    			foreach($areaArr as $res)
    			{
    			    $gameAreaId = $res['gameAreaId'];
    			    $this->initGameAreaInfo($gameAreaId);
    			    $url = "http://".$this->ipAddress.":".$this->httpPort."/game/services?action=mail&roleName=".$roleName
                                                                                    			    ."&minRoleLevel=".$minRoleLevel
                                                                                    			    ."&maxRoleLevel=".$maxRoleLevel
                                                                                    			    ."&itemString=".$itemString
                                                                                    			    ."&title=".$title
                                                                                    			    ."&content=".$content;
    			    error_log($url);
    			    file_get_contents($url);
    			}
			}
			
			$sql = "
				update
					`t_data_send_mail`
				set
					`status` = '{$status}',
					`approvalUserId` = '{$this->currUserId}',
					`approvalDatetime` = now()
				where
					`applyId` = '{$applyId}'
					and
					`status` = 1
			";
			$this->gmDatabase->query($sql);
		}
		
		catch(MY_Param_Exception $e) {
			$this->setErrorCode($e->getCode());
		}
		
		catch(MY_Mysql_Exception $e) {
			$this->setErrorCode(1);
		}
		
		catch(Exception $e) {
			$this->setErrorCode($e->getCode());
		}
		
		$this->returnJson();
		log_message('debug', '=====调用Mail->send->approval接口结束=====');
	}
	
	public function getInfoData() {
		log_message('debug', '=====开始调用Mail->Send->getInfoData接口=====');
		
		try {
			$applyId = $this->param->getParam('applyId', array('method' => 'int', 'min' => 1, 'emptyErrorCode' => 1, 'invalidErrorCode' => 1));
			$page = $this->param->getParam('page', array('method' => 'int', 'min' => 1, 'emptyErrorCode' => 1, 'invalidErrorCode' => 1));
			$rows = $this->param->getParam('rows', array('method' => 'int', 'min' => 1, 'emptyErrorCode' => 1, 'invalidErrorCode' => 1));
			
			$sql = "
				select
					<selectColumns>
				from
					`t_data_send_mail_game_area` a
				left join
					`t_data_game_area` b
				on
					a.`gameAreaId` = b.`gameAreaId`
				left join
					`t_data_operator` c
				on
					b.`operatorId` = c.`operatorId`
				where
					a.`applyId` = '{$applyId}'
			";
			$getTotalSql = str_replace('<selectColumns>', "count(*)", $sql);
			$this->returnData['data']['total'] = $this->gmDatabase->getColumn($getTotalSql);
			$getDataSql = str_replace('<selectColumns>', "c.`operatorName`, b.`areaNum`, a.`status`", $sql);
			
			if($page && $rows) {
				$startRow = ($page - 1) * $rows;
				$getDataSql .= " limit {$startRow}, {$rows}";
			}
				
			$this->returnData['data']['rows'] = $this->gmDatabase->getArray($getDataSql);
		}
		
		catch(MY_Param_Exception $e) {
			$this->setErrorCode($e->getCode());
		}
		
		catch(MY_Mysql_Exception $e) {
			$this->setErrorCode(1);
		}
		
		catch(Exception $e) {
			$this->setErrorCode($e->getCode());
		}
		
		$this->returnJson();
		log_message('debug', '=====调用Mail->Send->getInfoData接口结束=====');
	}
}